package com.lonni.rpc.core.loadbalance.wheel;

import com.lonni.rpc.core.model.RpcRequest;
import com.lonni.rpc.core.loadbalance.AbstractLoadBalance;
import com.lonni.rpc.core.model.ServiceAddress;

import java.util.List;

/**
 * 循序轮询
 * 使用标识和总节点取魔数即可
 *
 * @author: lonni
 * @CreateTime: 2024-06-27  21:17
 * @Description:
 */
public class RoundRobinLoadBalance extends AbstractLoadBalance {
    /**
     * 轮询标识
     */
    private static volatile Integer INDEX = 0;

    /**
     * 查询地址
     *
     * @param uris
     * @param request
     * @return
     */
    @Override
    public ServiceAddress doSelectAddress(List<ServiceAddress> uris, RpcRequest request) {
        int size = uris.size();
        int tempIndex = 0;
        synchronized (this) {
            if (INDEX >= size) {
                INDEX = 0;
            }
            tempIndex = INDEX % size;
            INDEX++;
        }

        return uris.get(tempIndex);
    }
}
